﻿#include "Coin.h"
#include "CoinManager.h"
using namespace cocos2d;
using namespace cocos2d::ui;
using namespace cocostudio::timeline;
Coin::Coin(Vec2 enemyPos, int coinNum, bool isGameCoin, bool isPerformWonders)
	:coinPos(enemyPos), 
	//coinNum(coinNum),
	isGameCoin(isGameCoin),
	isPerformWonders(isPerformWonders)
{

}
Coin* Coin::create(Vec2 enemyPos, int coinNum, bool isGameCoin, bool isPerformWonders) {
	Coin* ret = new (std::nothrow) Coin(enemyPos, coinNum, isGameCoin, isPerformWonders);
	if (ret && ret->init()) {
		ret->autorelease();
		return ret;
	}
	CC_SAFE_DELETE(ret);
	return nullptr;
}

bool Coin::init() {
	if (!Widget::init()) {
		return false;
	}
	size = Director::getInstance()->getVisibleSize();
	loadUserInfo();
	initCSBFile();
	return true;
}

/*
	加载用户信息
*/
void Coin::loadUserInfo() {
	int coinValue = UserDefault::getInstance()->getIntegerForKey("coin_value", 50);
	int profitValue = UserDefault::getInstance()->getIntegerForKey("profit_value", 5);
	coinNum = coinValue + coinValue * (profitValue / 100.0);
	//if (coinNum == 1000) {
	//	coinNum = coinNum + coinNum * (profitValue / 100.0);
	//} else {
	//	coinNum = coinValue + coinValue * (profitValue / 100.0);
	//}
	
}

/*
	加载CSB文件
*/
void Coin::initCSBFile() {
	coinNode = CSLoader::createNode("scenes/game/ui/coin.csb");
	coinSp = dynamic_cast<Sprite*>(coinNode->getChildByName("coin"));
	coinSize = coinSp->getContentSize();
	this->addChild(coinNode);
	coinSp->setPosition(coinPos);

	ActionTimeline* coinAct = CSLoader::createTimeline("scenes/game/ui/coin.csb");
	coinAct->play("coinAct", true);
	coinSp->runAction(coinAct);
}

/*
	金币飞行动画
*/
void Coin::runCoinAction(Vec2 pos) {
	Vec2 flyTagPos;
	if (isGameCoin) {
		flyTagPos = Vec2(124, 749);
	} else {
		flyTagPos = Vec2(44, 931);
	}
	float time1 = coinPos.getDistance(pos) / 200;
	MoveTo* mt1 = MoveTo::create(time1, pos);;
	coinPos = pos;

	//计算记录所需要的的时间
	float time2 = pos.getDistance(flyTagPos) / 350;

	//动画结束回收自己
	CallFunc* call = CallFunc::create([this]() {
		_eventDispatcher->dispatchCustomEvent("onCoinActFinish", this);
		CoinManager::getInstance()->collection(this);
	});

	//运行移动到金币图标动画坐标:(124,821)
	MoveTo* mt2 = MoveTo::create(time2, flyTagPos);
	Sequence* seqAct = Sequence::create(mt1, mt2, call, nullptr);
	coinSp->runAction(seqAct);
}